# import time  # 代码运行停顿
#
# import pytesseract  # 用于图片转文字
# from PIL import Image
# from selenium.webdriver import Chrome  # 用于打开网站
# from selenium.webdriver.common.by import By
#
#
# class VerificationCode:
#     def __init__(self):
#         self.driver = Chrome()
#
#     def get_pictures(self):
#         self.driver.get('https://auditsecdr.group.cpic.com/')  # 打开登陆页面
#         time.sleep(6)
#         self.driver.find_element(By.XPATH, '//*[@id="captcha_image"]').screenshot("anxin.png")
#
#     def image_str(self):
#         self.get_pictures()
#
#         pytesseract.pytesseract.tesseract_cmd = r"D:\ocr\tesseract.exe"
#         image = Image.open("anxin.png")
#         result = pytesseract.image_to_string(image)
#         print(result)
#
#
# if __name__ == '__main__':
#     a = VerificationCode()
#     a.image_str()


import cv2 as cv
import pytesseract
from PIL import Image


def recognize_text(image):
    # 边缘保留滤波  去噪
    dst = cv.pyrMeanShiftFiltering(image, sp=10, sr=150)
    # 灰度图像
    gray = cv.cvtColor(dst, cv.COLOR_BGR2GRAY)
    # 二值化
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
    # 形态学操作   腐蚀  膨胀
    erode = cv.erode(binary, None, iterations=2)
    dilate = cv.dilate(erode, None, iterations=1)
    cv.imshow('dilate', dilate)
    # 逻辑运算  让背景为白色  字体为黑  便于识别
    cv.bitwise_not(dilate, dilate)
    cv.imshow('binary-image', dilate)
    # 识别
    test_message = Image.fromarray(dilate)
    text = pytesseract.image_to_string(test_message)
    print(f'识别结果：{text}')


src = cv.imread(r'anxin.jpg')
cv.imshow('input image', src)
recognize_text(src)
cv.waitKey(0)
cv.destroyAllWindows()
